﻿using System;
using System.Collections.Generic;
using System.Linq;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Models;
using Newtonsoft.Json;

namespace Atmk.WaterMeter.MIS.Logic
{
    /// <summary>
    /// 角色权限管理
    /// </summary>
    public class RolesLogic:IRolesLogic
    {
        private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly IRepository _repository;
        private readonly IRolesRepository _rolesRepository;

        public RolesLogic(
            IRepository repository,
            IRolesRepository rolesRepository
        )
        {
            _repository = repository;
            _rolesRepository = rolesRepository;
        }
        /// <summary>
        /// 查询所有角色信息
        /// </summary>
        /// <returns></returns>
        public  object SelectRoles()
        {
            var roles = _rolesRepository.GetRoleExceptAdmin();
            var result = new object[roles.Count];
            for (var i = 0; i < roles.Count; i++)
            {
                result[i] = new
                {
                    id = roles[i].Id.ToString(),
                    roleName = roles[i].Name,
                    remark = roles[i].Memo ?? ""
                };
            }
            return result;
        }

        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// <param name="role"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public  bool AddRoles(dynamic role, out string exception,out string id)
        {
            exception = "";
            id = "";
            try
            {
                var roleName = role.roleName.ToString();
                var roles = Enumerable.ToList<Roles>(_repository.FindAll<Roles>());
                if (roles.Any(r => r.Name == roleName))
                {
                    exception = "角色名称重复";
                    _logger.Warn(exception);
                    return false;
                }
                var roleEntity = new Roles()
                {
                    Memo = role.remark.ToString()
                };
                id = roleEntity.Id.ToString();
                if (_repository.Add(roleEntity) > 0)
                    return true;
                exception ="添加失败";
                _logger.Warn(exception);
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public  bool UpdateRoles(dynamic obj, out string exception)
        {
            exception = "";
            try
            {
              
                var roles = Enumerable.ToList<Roles>(_repository.FindAll<Roles>());
                if (roles.Count == 0)
                {
                    exception = "没有角色信息";
                    _logger.Warn(exception);
                    return false;
                }
                var role = roles.First(r => r.Id.ToString() == obj.id.ToString());
                role.Name = obj.roleName.ToString();
                role.Memo = obj.remark.ToString();
                if (_repository.Update(role) > 0)
                    return true;
                exception = "修改失败";
                _logger.Warn(exception);
                return false;
            }
            catch (Exception e)
            {
                exception = e.Message;
                _logger.Error(e);
                return false;
            }
        }

        /// <summary>
        /// 删除角色信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public  bool DeleteRole(string id, out string exception)
        {
            try
            {
                exception = null;
                if (Enumerable.Count<Roles>(_repository.FindAll<Roles>(),
                        r => r.Id.ToString() == id) == 0)
                {
                    exception = ("没有角色信息");
                    _logger.Warn(exception);
                    return false;
                }
                var role = Enumerable.First<Roles>(_repository
                    .FindAll<Roles>(), r => r.Id.ToString() == id);
                if (_repository.FindAll<User>().Any<User>(s => s.RoleId == role.Id.ToString()))
                {
                    exception = "删除失败,有操作员使用该权限";
                    _logger.Warn(exception);
                    return false;
                }
                if (_repository.Remove(role) > 0)
                    return true;
                exception = "删除失败";
                _logger.Warn(exception);
                return false;
            }
            catch (Exception e)
            {
                exception = e.Message;
                _logger.Error(e);
                return false;
            }
        }

        /// <summary>
        /// 获取权限信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public  object SelectParmissions(string id)
        {
            try
            {
                var roles = Enumerable.Where<Roles>(_repository.FindAll<Roles>(),
                    r => r.Id.ToString() == id).ToList();
                if (!roles.Any())
                {
                    throw new Exception("SelectParmissions:没有角色，无法获取权限信息");
                }
                var role = roles.First();
                var parmissions = role.Parmissions?.Trim();
                object authList = null;
                authList = !string.IsNullOrEmpty(parmissions)
                    ? JsonConvert.DeserializeObject(parmissions)
                    : new List<object>();
                var result = new
                {
                    id = role.Id.ToString(),
                    authList
                };
                return result;
            }
            catch (Exception e)
            {
                throw new Exception($"SelectParmissions:{e.Message}");
            }
        }

        /// <summary>
        /// 修改权限信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="authList"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public  object UpdateParmissions(string id, string authList, out string exception)
        {
            try
            {
                exception = "";
                var roles = Enumerable.Where<Roles>(_repository.FindAll<Roles>(),
                    r => r.Id.ToString() == id).ToList();
                if (!roles.Any())
                {
                    exception = "没有角色，无法获取权限信息";
                    _logger.Warn(exception);
                    return false;
                }
                var role = roles.First();
                role.Parmissions = authList;
                if (_repository.Update(role) > 0)
                    return true;
                exception = "授权设置失败";
                _logger.Warn(exception);
                return false;
            }
            catch (Exception e)
            {
                exception = e.Message;
                _logger.Error(e);
                return false;
            }
        }
    }
}